package net.homeftp.heimo.weddingwidget;

import net.homeftp.heimo.weddingwidget.core.DateHelper;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;

public class WeddingWidgetService extends Service {
	private final IBinder mBinder = new LocalBinder();
	private static final String TAG = "WeddingWidgetService";
	
	private AlarmManager alarmManager = null;
	private PendingIntent pi = null;
	
	@Override
    public void onCreate() {
		Log.d(TAG, "[onCreate]");
		super.onCreate();
		pi = this.getPi();
    }
	
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		Log.d(TAG, "[onStartCommand]");
		handleCommand(intent);
	    return super.onStartCommand(intent, flags, startId);
	}

	
	private void handleCommand(Intent intent) {		
		long milliisTarget = DateHelper.getAlarmWakeUpTime();
		alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
		alarmManager.set(AlarmManager.RTC_WAKEUP, milliisTarget, pi);
	}
	
	@Override
	public void onDestroy(){
		super.onDestroy();
		Log.d(TAG, "[onDestroy]");
		if(this.pi!=null){
			alarmManager.cancel(pi);
		}
	}
	
	@Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }
		
	public class LocalBinder extends Binder {
		WeddingWidgetService getService() {
            return WeddingWidgetService.this;
        }
    }
	
	/*
	 * Private function
	 * */
	
	private PendingIntent getPi(){
		Intent i = new Intent(this, WeddingWidgetProvider.class);
		String eventName = this.getApplicationContext().getResources().getString(R.string.widget_event_name);
		i.setAction(eventName);
		return PendingIntent.getBroadcast(this, 0, i,PendingIntent.FLAG_CANCEL_CURRENT);
	}
}
